import {
	defineStore
} from "pinia";

import {
	ref
} from "vue";

import {
	getUserPostAPI,
	createPostAPI,
	saveDraftAPI
} from "../apis/postAPI";

export const usePostStore = defineStore("post", () => {
	let posts = ref([]);
	let mediaList = ref([]);
	let formData = ref({
		title: "",
		content: ""
	});

	const selectedCategoryId = ref(null);

	//更新媒体列表
	const updateMediaList = (files) => {
		mediaList.value = [...mediaList.value, ...files];
	}

	// 更新选中分类
	const setSelectedCategoryId = (categoryId) => {
		selectedCategoryId.value = categoryId;
	};

	/**
	 * 提交帖子
	 * @param {Object} postData 帖子数据
	 */
	const submitPost = async () => {
		let postData = new FormData();
		postData.append("title", formData.value.title);
		postData.append("content", formData.value.content);
		postData.append("categoryId", selectedCategoryId.value);


		// 添加图片
		mediaList.value.forEach((item) => {
			let rawFile = item.file; // 直接使用存储的File对象
			postData.append("images", rawFile, rawFile.name);
		});

		try {
			let res = await createPostAPI(postData);

			await getPostsByUserId(res.data.data.userId)

			uni.showToast({
				title: "发布成功",
				icon: "none",
				duration: 2000
			});

			clearForm();

			return res
		} catch (error) {
			console.error(error);
			uni.showToast({
				title: "发布失败",
				icon: "none",
				duration: 2000
			})
		};
	}

	/**
	 * 保存草稿
	 * @param {Object} postData 帖子数据
	 */
	const saveDraft = async () => {
		let postData = new FormData();
		postData.append("title", formData.value.title);
		postData.append("content", formData.value.content || "");
		if (selectedCategoryId.value) {
			postData.append("categoryId", selectedCategoryId.value);
		}

		// 添加图片
		mediaList.value.forEach((item) => {
			let rawFile = item.file; // 直接使用存储的File对象
			postData.append("images", rawFile, rawFile.name);
		});

		try {
			let res = await saveDraftAPI(postData);

			await getPostsByUserId(res.data.data.userId)

			uni.showToast({
				title: "草稿保存成功",
				icon: "none",
				duration: 2000
			});

			clearForm();

			return res
		} catch (error) {
			console.error(error);
			uni.showToast({
				title: "草稿保存失败",
				icon: "none",
				duration: 2000
			})
		};

	}

	/**
	 * 根据用户 id 获取用户帖子
	 * @param {String} userId 用户id
	 */
	const getPostsByUserId = async (userId) => {
		try {
			const res = await getUserPostAPI(userId)

			posts.value = res.data.data;

		} catch (error) {
			console.error('获取用户信息失败:', error)
		}

	}

	/**
	 * 根据帖子状态获取帖子
	 * @param {String} status 帖子状态
	 */
	const getPostsByStatus = (status) => {
		return posts.value.filter(post => post.postStatus === status);
	};

	/**
	 * 清空表单
	 */
	const clearForm = () => {
		formData.value = {
			title: "",
			content: ""
		};
		mediaList.value = [];
		selectedCategoryId.value = null;
	}

	// 初始化帖子
	const init = () => {
		const savedState = uni.getStorageSync('post');

		if (savedState) {
			posts.value = savedState.posts || [];
			mediaList.value = savedState.mediaList || [];
			formData.value = savedState.formData || {
				title: "",
				content: ""
			};
			selectedCategoryId.value = savedState.selectedCategoryId || null;
		}
	};

	return {
		posts,
		mediaList,
		formData,
		selectedCategoryId,
		updateMediaList,
		setSelectedCategoryId,
		submitPost,
		saveDraft,
		getPostsByUserId,
		getPostsByStatus,
		clearForm,
		init
	}
}, {
	persist: true
});